package com.ruoyi.jeeplus.modules.screen.frontdesk.screen_charge.service.impl;

import com.alibaba.fastjson2.JSONWriterUTF16JDK8UF;
import com.ruoyi.jeeplus.modules.screen.frontdesk.screen_PV.domain.Frontdesk_screen_PV;
import com.ruoyi.jeeplus.modules.screen.frontdesk.screen_charge.domain.Frontdesk_screen_chargeNew;
import com.ruoyi.jeeplus.modules.screen.frontdesk.screen_charge.mapper.Frontdesk_screen_chargeMapper;
import com.ruoyi.jeeplus.modules.screen.frontdesk.screen_charge.service.IFrontdesk_screen_chargeService;
import com.ruoyi.jeeplus.modules.screen.screen_charge.domain.screen_charge;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 刘奥旸
 * @version 1.0
 */
@Service
public class Frontdesk_screen_chargeServiceImpl implements IFrontdesk_screen_chargeService {

    @Autowired
    Frontdesk_screen_chargeMapper frontdeskScreenChargeMapper;

    public String getTodayDate(int id) {
        LocalDate today = LocalDate.now();
        String result;
        switch (id) {
            case 0:
                //完成拼接数据查询
                result = "%";
                break;
            case 1:
                result = String.valueOf(today.getYear()); // 返回年
                result = result + "%";
                break;
            case 2:
                result = today.format(DateTimeFormatter.ofPattern("yyyy-MM")); // 返回年月
                result = result + "%";
                break;
            case 3:
                result = today.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")); // 返回年月日
                result = result + "%";
                break;
            default:
                result = "无效的格式"; // 处理无效的参数
        }
        // System.out.println("result==" + result);
        return result;
    }

    //奥旸算法开始咯：共用！！！！！！！！！！！！

    public List<Frontdesk_screen_chargeNew> together(String a, String date, int d) {

        //String c = getTodayDate(b);
        if (a.equals("3")) {
            a = "%";
        }

//        System.out.println(c+ "aaaaaaaaaaaaaaaaaa");
//        System.out.println(d+"bbbbbbbbbbbbbbbbbbbbb");
//        System.out.println("cccccccccccccc"+frontdeskScreenChargeMapper.selectScreenCharge(a,c));
        //System.out.println("aaaaaaaaaaaaaaaaaaa========" +a);
        List<Frontdesk_screen_chargeNew> frontdeskScreenChargeNews = frontdeskScreenChargeMapper.selectScreenCharge(a, date);
        List<Frontdesk_screen_chargeNew> collect = frontdeskScreenChargeNews.stream().filter(categoryEntity -> {
            //这里改一下就行了就差这里了
            // return categoryEntity.getBelongRegion().equals("100000");
            return categoryEntity.getBelongRegion() == d;
            //    return categoryEntity.getParentId() == 0;
        }).map(category -> {
            category.setChildrenCategories(getChildrenCategories(category, frontdeskScreenChargeNews));
            return category;
        }).collect(Collectors.toList());
//        System.out.println("Before calPV: " + collect);
        calPV(collect);
//        System.out.println("After calPV: " + collect);
        return collect;

    }
        public HashMap<String, Object> month_day(String two_four, int date, int id){
            ArrayList<Double> pv_countlist = new ArrayList<>();
            ArrayList<Double> normal_countlist = new ArrayList<>();
            Double count = new Double(0);
            //String todayDate = getTodayDate(3);

            LocalDate today = LocalDate.now();
            String currentDate = today.format(DateTimeFormatter.ofPattern("yyyy-MM")); // 返回年月
            int year = Integer.parseInt(currentDate.substring(0, 4)); // 提取年份
            int month = Integer.parseInt(currentDate.substring(5, 7)); // 提取月份
            for (int day = 1; day <= 30; day++) {

                // 假设最多30天
                String formattedDate = String.format("%04d-%02d-%02d", year, month, day);
                formattedDate = formattedDate + "%";
               //System.out.println(formattedDate); // 输出格式为 "2024-10-01", "2024-10-02", ...
                List<Frontdesk_screen_chargeNew> together = together(two_four, formattedDate, id);
                if (!together.isEmpty()) {
                    Double pvSelling = together.get(0).getPvSelling();
                    Double normalSelling = together.get(0).getNormalSelling();

                    pv_countlist.add(pvSelling);
                    normal_countlist.add(normalSelling);
                    // 处理 pvGeneration\
                }else {
                    pv_countlist.add(count);
                }
                System.out.println("pv_countlist==" + pv_countlist);
                System.out.println("normalSelling==" + normal_countlist);
                // System.out.println(currentDate);
            }
            List<Double> pv_summedData = new ArrayList<>();
            List<Double> normal_summedData = new ArrayList<>();
            // 遍历原始数据，两个两个相加
            for (int i = 0; i < pv_countlist.size(); i += 5) {
                Double sum = new Double(0); // 初始化总和
                for (int j = 0; j < 5; j++) { // 处理5个元素
                    if (i + j < pv_countlist.size()) { // 确保索引不越界
                        sum = sum + pv_countlist.get(i + j); // 累加
                    }
                }
                pv_summedData.add(sum); // 将每组的和添加到 summedData
            }
            for (int i = 0; i < normal_countlist.size(); i += 5) {
                Double sum = new Double(0); // 初始化总和
                for (int j = 0; j < 5; j++) { // 处理5个元素
                    if (i + j < normal_countlist.size()) { // 确保索引不越界
                        sum = sum + normal_countlist.get(i + j); // 累加
                    }
                }
                normal_summedData.add(sum); // 将每组的和添加到 summedData
            }
            System.out.println(normal_summedData);
            HashMap<String, Object> summedData = new HashMap<>();
            summedData.put("summedPvData" , pv_summedData);
            summedData.put("summedNormalData" , normal_summedData);
            return summedData;
}

    public Map<String, Object> a32(String two_four, int date, String id_string) {
        int id = Integer.parseInt(id_string);

        if (date == 4) {
         return status_time(two_four,date,id);
        }else if (date == 5){

            return month_day(two_four, date, id);
        }

        String c = getTodayDate(date);
        if (two_four.equals("3")) {
            two_four = "%";
        }

        //System.out.println("aaaaaaaaaaaaaaaaaaa========" +a);
        List<Frontdesk_screen_chargeNew> frontdeskScreenChargeNews = frontdeskScreenChargeMapper.selectScreenCharge(two_four, c);

        List<Frontdesk_screen_chargeNew> collect = frontdeskScreenChargeNews.stream().filter(categoryEntity -> {
            //这里改一下就行了就差这里了
            // return categoryEntity.getBelongRegion().equals("100000");
            return categoryEntity.getBelongRegion() == id;
            //    return categoryEntity.getParentId() == 0;
        }).map(category -> {
            category.setChildrenCategories(getChildrenCategories(category, frontdeskScreenChargeNews));
            return category;
        }).collect(Collectors.toList());
        calPV(collect);
        //省的报错，提前返回
        if (collect.isEmpty()) {
            return null;
        }
        BigDecimal totalCharging = collect.get(0).getTotalCharging();
        Double pvSelling = collect.get(0).getPvSelling();
        Double normalSelling = collect.get(0).getNormalSelling();
        Double Totalselling = pvSelling + normalSelling;
        Double pv_ratio = pvSelling / (pvSelling + normalSelling);
        Double normal_ratio = normalSelling / (pvSelling + normalSelling);
        DecimalFormat df = new DecimalFormat("0.00%");
        String pv_ratio_percentage = df.format(pv_ratio);
        String normal_ratio_percentage = df.format(normal_ratio);
        //创建map返回
        Map<String, Object> kvMap = new HashMap<>();

        // 添加键值对
        kvMap.put("pvSelling", pvSelling);
        kvMap.put("normalSelling", normalSelling);
        kvMap.put("pv_ratio_percentage", pv_ratio_percentage);
        kvMap.put("normal_ratio_percentage", normal_ratio_percentage);
        kvMap.put("Totalselling", Totalselling);
        //结束
        //System.out.println(pv_ratio_percentage + "ssssssssss" +normal_ratio_percentage);
        return kvMap;
    }

    //刘奥旸算法开始咯：
    //递归查找所有分类的分类getChildrenCategories(categoryEntity, all)
    private List<Frontdesk_screen_chargeNew> getChildrenCategories
    (Frontdesk_screen_chargeNew root, List<Frontdesk_screen_chargeNew> all) {
        List<Frontdesk_screen_chargeNew> children = all.stream().filter(categoryEntity -> {
            //寻找其子类，必须用equals
            return categoryEntity.getParentId().equals(root.getBelongRegion());
        }).map(categoryEntity -> {

            //1、找到子菜单, 并设置
            categoryEntity.setChildrenCategories(getChildrenCategories(categoryEntity, all));

            return categoryEntity;
        }).collect(Collectors.toList());

        return children;
    }

    private void calPV(List<Frontdesk_screen_chargeNew> all) {
        // 遍历所有分类
        for (Frontdesk_screen_chargeNew node : all) {
            // 检查当前节点是否有子类
            if (node.getChildrenCategories() != null && !node.getChildrenCategories().isEmpty()) {
                // 递归调用，计算子类的 PV 值
                calPV(node.getChildrenCategories());

                // 计算子类的总 PV 值
                Double totalPvSelling = node.getChildrenCategories().stream()
                        .map(Frontdesk_screen_chargeNew::getPvSelling) // 提取每个子类的 PV 值
                        .filter(Objects::nonNull) // 过滤掉 null 值，避免计算错误
                        .reduce(0.0, Double::sum); // 计算总和，初始值为 0.0

                // 计算子类的总 normalSelling 值
                Double totalNormalSelling = node.getChildrenCategories().stream()
                        .map(Frontdesk_screen_chargeNew::getNormalSelling) // 提取每个子类的 normalSelling 值
                        .filter(Objects::nonNull) // 过滤掉 null 值，避免计算错误
                        .reduce(0.0, Double::sum); // 计算总和，初始值为 0.0

                // 计算子类的总充电量
                BigDecimal totalCharging = node.getChildrenCategories().stream()
                        .map(Frontdesk_screen_chargeNew::getTotalCharging) // 提取每个子类的总充电量
                        .filter(Objects::nonNull) // 过滤掉 null 值，避免计算错误
                        .reduce(BigDecimal.ZERO, BigDecimal::add); // 计算总和，初始值为 0

                // 将子类总 PV 加到当前节点的 PV 中
                node.setPvSelling(totalPvSelling + (node.getPvSelling() != null ? node.getPvSelling() : 0.0));
                // 将子类总 normalSelling 加到当前节点的 normalSelling 中
                node.setNormalSelling(totalNormalSelling + (node.getNormalSelling() != null ? node.getNormalSelling() : 0.0));
                // 将子类总充电量加到当前节点的总充电量中
                node.setTotalCharging(totalCharging.add(node.getTotalCharging() != null ? node.getTotalCharging() : BigDecimal.ZERO));
            }
        }
    }


    public  Map<String, Object> status_time(String two_four, int date, int id) {
        if (date == 4) {
            Map<String, Object> kvMap = new HashMap<>();
            ArrayList<Double> pv_countlist = new ArrayList<>();
            ArrayList<Double> normal_countlist = new ArrayList<>();
//            ArrayList<BigDecimal> countlist = new ArrayList<>();
            //String todayDate = getTodayDate(3);
            Double normalSelling;
            Double pvSelling;
            //自己的方法
            String new_date = getTodayDate(date);
            if (two_four.equals("3")) {
                two_four = "%";
            }
            String currentDate = getTodayDate(3); // 假设这个方法返回类似 "2024-10-24" 的字符串
            for (int i = 8; i <= 19; i++) {
                //todayDate = todayDate + " " + i;
                BigDecimal count = new BigDecimal(0);
                String todayDate = String.format("%s %02d", currentDate, i);
                todayDate = todayDate + "%";
               // System.out.println(todayDate);

                List<Frontdesk_screen_chargeNew> together = together(two_four, todayDate, id);

                if (!together.isEmpty()) {
                    normalSelling = together.get(0).getNormalSelling();
                    pvSelling = together.get(0).getPvSelling();
                    pv_countlist.add(pvSelling);
                    normal_countlist.add(normalSelling);
                }
            }
            //都是处理12->6
            // 创建返回数组
            List<Double> summedPvData = new ArrayList<>();
            List<Double> summedNormalData = new ArrayList<>();
// 处理 pv_countlist
            for (int i = 0; i < pv_countlist.size(); i += 2) {
                double pvSum = 0.0;
                if (i + 1 < pv_countlist.size()) {
                    // 计算两个元素的和
                    pvSum = pv_countlist.get(i) + pv_countlist.get(i + 1);
                    summedPvData.add(pvSum);
                } else {
                    // 如果是最后一个元素且没有配对，则单独添加
                    summedPvData.add(pv_countlist.get(i));
                }
            }

            // 处理 normal_countlist
            for (int i = 0; i < normal_countlist.size(); i += 2) {
                double normalSum = 0.0;
                if (i + 1 < normal_countlist.size()) {
                    // 计算两个元素的和
                    normalSum = normal_countlist.get(i) + normal_countlist.get(i + 1);
                    summedNormalData.add(normalSum);
                } else {
                    // 如果是最后一个元素且没有配对，则单独添加
                    summedNormalData.add(normal_countlist.get(i));
                }
            }

            // 将这些 List 插入到 kvMap 中
            kvMap.put("summedPvData", summedPvData);
            kvMap.put("summedNormalData", summedNormalData);
            System.out.println(kvMap);
            return kvMap;
        }
        return null;
    }

}
